<?php

namespace App\Http\Controllers\Api\V1;

use Carbon\Carbon;
use App\Models\Coupon;
use App\Services\TransferBrokerageToBalance\TransferBrokerageToBalance;
use Illuminate\Support\Facades\Cache;
use App\Services\Cache\BrokerageCache;
use App\Http\Controllers\Api\V1\Resources\CouponResource;
use Illuminate\Database\Eloquent\Builder;

class CouponsController extends Controller
{
	public function index()
	{
		$user = request()->user();
		$is_used = request('used');
		$source = request('source');

		if($is_used){
			$list = $user->coupons()
				->join('coupons','coupons.id','user_coupons.coupon_id')
				->where(function (Builder $query) {
							$query->where('coupon_category','common')
							->orWhere('coupon_category','box');
					})
				->where(function (Builder $query) {
					$query->where('is_used', 1)
						->orWhere('destory_at','<',Carbon::now());
					})
				->orderByDesc('user_coupons.id')->paginate();


		}else{
			

			$list = $user->coupons()
				->join('coupons','coupons.id','user_coupons.coupon_id')
				->where('is_used', 0)
				->where('destory_at','>',Carbon::now())
				->where(function (Builder $query) {
						$query->where('coupon_category','common')
						->orWhere('coupon_category','box');
				})
				->orderByDesc('user_coupons.id')
				->paginate();
			
			
		}
		

		return CouponResource::collection($list);
	}


	public function default()
	{
		$user = request()->user();
		$source = request('source');
		$total  = request('total') ?? 0;

		if($source=='box'){
			$list = $user->coupons()
				->join('coupons','coupons.id','user_coupons.coupon_id')
				->where('is_used', 0)
				->where('destory_at','>',Carbon::now())
				->where('coupon_category','box')
				->where('full_price','<=',$total)
				->orderByDesc('user_coupons.id')
				->select('user_coupons.*','coupons.coupon_category','coupons.full_price','coupons.decrement_price','coupons.name')
				->get();
		}elseif($source=='common'){
			$list = $user->coupons()
				->join('coupons','coupons.id','user_coupons.coupon_id')
				->where('is_used', 0)
				->where('destory_at','>',Carbon::now())
				->where('coupon_category','common')
				->where('full_price','<=',$total)
				->orderByDesc('user_coupons.id')
				->select('user_coupons.*','coupons.coupon_category','coupons.full_price','coupons.decrement_price','coupons.name')
				->get();
		}

		return response()->json(['list' => $list]);
	}
	
}
